package com.heima.article.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private IWemediaClient weMediaClient;

    /**
     * 计算文章的分值
     */
    @Override
    public void computeHotArticle() {
        // 1. 查询前五天的文章数据
        Date fiveDaysAgo = LocalDateTime.now().minusDays(5).toDate(); // 前五天

        List<ApArticle> apArticles = apArticleMapper.findArticleListByLast5days(fiveDaysAgo);

        // 2. 计算文章分值(阅读:1, 点赞:3, 评论:5, 收藏:8)
        List<HotArticleVo> collect = apArticles.stream().map(this::computeScore).collect(Collectors.toList());

        // 3. 缓存每个频道分值最高的30条文章信息
        cacheTagToRedis(collect);

    }

    /**
     * 为每个频道缓存30条分值较高的文章
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        // 获取所有频道
        ResponseResult<List<WmChannel>> responseResult = weMediaClient.getChannels();

        // 每个频道缓存30条分值较高的文章
        if (responseResult.getCode().equals(200)) {
            String channelJson = JSON.toJSONString(responseResult.getData());
            List<WmChannel> wmChannels = JSON.parseArray(channelJson, WmChannel.class);
            // 检索出每个频道的文章
            if (wmChannels != null && !wmChannels.isEmpty()) {
                for (WmChannel wmChannel : wmChannels) {
                    List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                            .filter(x -> x.getChannelId().equals(wmChannel.getId()))
                            .collect(Collectors.toList());
                    //给文章进行排序，取30条分值较高的文章存入redis  key：频道id   value：30条分值较高的文章
                    sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId());
                }
            }
        }
    }

    // 排序并缓存文章信息
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        List<HotArticleVo> collect = hotArticleVos.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed()) // 降序
                .collect(Collectors.toList());
        if (collect.size() > 30) {
            collect = collect.subList(0, 30);
        }
        cacheService.set(key, JSON.toJSONString(collect));
    }

    // 计算文章分值
    private HotArticleVo computeScore(ApArticle apArticle) {
        HotArticleVo hotArticleVo = BeanUtil.copyProperties(apArticle, HotArticleVo.class);
        int score = 0;
        if (apArticle.getViews() != null) { // 阅读
            score += apArticle.getViews();
        }
        if (apArticle.getLikes() != null) { // 点赞
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getComment() != null) { // 评论
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection() != null) { // 收藏
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        hotArticleVo.setScore(score);
        return hotArticleVo;
    }
}
